package com.atguigu.ssyx.service;

import com.atguigu.ssyx.api.WgWebapi;
import com.atguigu.ssyx.model.WgRequest;
import com.atguigu.ssyx.model.WgResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OpenGateService {

    @Resource
    private WgWebapi wgWebapi;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public void openGate(Integer sn, Integer gateNo) {
        // 获取测试服务器URL和控制器序列号
        String url = WgWebapi.testUrl;         //"http://localhost:61080/";
//        int controllerSN = WgWebapi.testControllerSN;
        log.info("远程开门");
        String op = "远程开门";

        WgRequest cmdBody = new WgRequest();
        try {
            cmdBody.setJsonrpc("2.0");
            cmdBody.setMethod(op);
            List<WgRequest.Params> params = new ArrayList<>();
            WgRequest.Params params1 = new WgRequest.Params();
            params1.setSn(sn);
            params1.setGateId(gateNo);
            params.add(params1);
            cmdBody.setParams(params);
            cmdBody.setId(1001);

            String body = objectMapper.writeValueAsString(cmdBody).toString();
            WgResponse strResult = wgWebapi.PushToWebWithjson(url,body);
            // 处理响应结果
            if (strResult == null)
            {
                log.info("通信失败!");
            }
            else
            {
                // 判断操作是否成功
                boolean bvalid = wgWebapi.successIsTrue(strResult);
                if(bvalid) {
                    log.info(String.format("%d %s  %s ", sn, op,  "成功." ));
                }
                else
                {
                    log.info(String.format("%d %s  %s ", sn, op, "失败..."));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}